import os
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

# 要解密的文件夹路径
directory = 'D:/data/en'
# 解密后的文件夹路径
output_directory = os.path.abspath(
    os.path.join(directory, "..", directory+"_decrypted"))
if not os.path.exists(output_directory):
    os.makedirs(output_directory)
# 解密密钥，长度为16、24或32字节
key = b'your_key12345678your_key12345678'


def decrypt_file(file_path, output_path):
    """文件解密, 存到指定路径"""
    # 读取文件,解密文件内容
    with open(file_path, 'rb') as f_in:
        # ECB 对象
        cipher = AES.new(key, AES.MODE_ECB)
        decrypted_data = unpad(cipher.decrypt(f_in.read()), AES.block_size)

    # 写入解密后的文件
    with open(output_path, 'wb') as f_out:
        f_out.write(decrypted_data)


def handle_directory(directory, output_directory):
    """文件加及文件处理"""
    root_dir_list = os.listdir(directory)
    for name in root_dir_list:
        file_path = os.path.join(directory, name)
        # 处理子目录
        if os.path.isdir(file_path):
            output_path = os.path.join(output_directory, name)
            # 创建文件夹
            if not os.path.exists(output_path):
                os.makedirs(output_path)
            handle_directory(file_path, output_path)
        # 处理文件
        else:
            output_path = os.path.join(output_directory, name)
            decrypt_file(file_path, output_path)


if __name__ == '__main__':
    handle_directory(directory, output_directory)
